module EasyForm
  module Helpers
    module Validators

      def has_validators?
        @has_validators ||= attribute_name && object.class.respond_to?(:validators_on)
      end

      private
      def attribute_validators
        object.class.validators_on(attribute_name)
      end

      def reflection_validators
        reflection ? object.class.validators_on(reflection.name) : []
      end

      def valid_validator?(validator)
        !conditional_validators?(validator) && action_validator_match?(validator)
      end

      def conditional_validators?(validator)
        #model定义的验证是否有if或unless条件
        validator.options.include?(:if) || validator.options.include?(:unless)
      end

      # validator:
      # ActiveRecord::Validations::PresenceValidator
      # ActiveRecord::Validations::UniquenessValidator
      # ...
      def action_validator_match?(validator)
        return true unless validator.options.include?(:on)

        case validator.options[:on]
        when :save
          true
        when :create
          #没有持久化返回true
          !object.persisted? #persisted?和new_record?差不多,但返回结果相反
        when :update
          #有持久化返回true
          object.persisted?
        end
      end

      # #kind验证种类：
      # presence,uniqueness,length, numericality, ...
      def find_validator(kind)
        return unless has_validators?
        attribute_validators.find {|v| v.kind == kind}
      end
    end
  end
end